package com.bee.rbac.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.authc.AuthenticationException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import io.swagger.annotations.ApiOperation;

@Controller
public class LoginController {
	
	@RequestMapping("/login")
	@ApiOperation(value = "获取所有")
	public String login(){
		return "login";
	}

	
//	@PostMapping("/login")
//	public String postLogin(String username, String password){
//		System.out.println(username);
//		System.out.println(password);
//		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
//		SecurityUtils.getSubject().login(usernamePasswordToken);
//		return "redirect:/hello";
//	}
	
    private Logger logger = LoggerFactory.getLogger(this.getClass());

	@PostMapping("login")
    public String login(
            @RequestParam(value = "username", required = true) String userName,
            @RequestParam(value = "password", required = true) String password
    ) {
        logger.info("==========" + userName + password );
        
        System.out.println("login:"+passwordEncoder(password));
        
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
   

        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
//            rediect.addFlashAttribute("errorText", "您的账号或密码输入错误!");
            return "redirect:/err";
  
//            return "{\"Msg\":\"您的账号或密码输入错误\",\"state\":\"failed\"}";
        }
        return "redirect:/hello";
//        return "{\"Msg\":\"登陆成功\",\"state\":\"success\"}";
    }
	
	public String passwordEncoder(String credentials) {
		Object object = new SimpleHash("MD5", credentials, "rg",3);
		return object.toString();
	}



}
